package com.kimwu.rabbitmq.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.io.UnsupportedEncodingException;

/**
 * 生产者消息确认
 *
 * @author KimWu
 */
@Slf4j
public class RabbitConfirmCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("ConfirmCallback:     " + "相关数据：" + correlationData);
        log.info("ConfirmCallback:     " + "确认情况：" + ack);
        log.info("ConfirmCallback:     " + "原因：" + cause);
        if (ack) {
            log.info("消息发送确认成功");
        } else {
            String str = "【rabbitmq消息发送确认失败】 相关数据 : " + correlationData + ",确认情况 : " + ack + ",原因 : " + cause;
            log.info("消息发送确认失败");
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        //失败的回调
        try {
            log.info("ReturnCallback:     " + "消息：" + new String(message.getBody(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("ReturnCallback:     " + "回应码：" + replyCode);
        log.info("ReturnCallback:     " + "回应信息：" + replyText);
        log.info("ReturnCallback:     " + "交换机：" + exchange);
        log.info("ReturnCallback:     " + "路由键：" + routingKey);
        String str = null;
        try {
            str = "【rabbitmq消息回调失败】 消息 : " + new String(message.getBody(), "UTF-8") + ",回应码 : " + replyCode +
                    ",回应信息 :" + replyText + ",交换机 :" + exchange + ",路由键 :" + routingKey;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
